<template>
  <el-card
    shadow="always"
    :body-style="{ padding: '20px' }"
    :style="{ marginTop: '20px' }"
  >
    <el-form label-width="80px" :inline="false">
      <el-form-item label="SPU名称">
        <span>{{ props.spuInfo.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU名称">
        <el-input
          placeholder="请输入sku名称"
          clearable
          v-model="skuInfo.skuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input
          placeholder="请输入价格"
          clearable
          type="number"
          v-model="skuInfo.price"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量">
        <el-input
          placeholder="请输入重量"
          clearable
          type="number"
          v-model="skuInfo.weight"
        ></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input
          placeholder="请输入规格描述"
          clearable
          type="textarea"
          v-model="skuInfo.skuDesc"
        ></el-input>
      </el-form-item>

      <el-form-item label="平台属性">
        <el-form label-width="80px" :inline="true" size="small">
          <el-form-item
            v-for="attr in attrList"
            :key="attr.id"
            :label="attr.attrName"
          >
            <el-select
              placeholder="请选择"
              clearable
              filterable
              v-model="attr.attrIdValueId"
            >
              <el-option
                v-for="attrValue in attr.attrValueList"
                :key="attrValue.id"
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-form label-width="80px" :inline="true" size="small">
          <el-form-item
            v-for="saleAttr in saleAttrList"
            :key="saleAttr.id"
            :label="saleAttr.saleAttrName"
          >
            <el-select
              placeholder="请选择"
              clearable
              filterable
              v-model="saleAttr.saleAttrIdValueId"
            >
              <el-option
                v-for="spuSaleAttrValue in saleAttr.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
                :label="spuSaleAttrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${spuSaleAttrValue.id}`"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片列表">
        <el-table
          :data="spuImageList"
          border
          stripe
          @selection-change="handleSelectionChange"
          v-loading="loading"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" alt="" :style="{ height: '150px' }" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"> </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag v-if="row.isDefault" type="danger" effect="dark"
                >默认图片</el-tag
              >
              <el-button
                type="primary"
                v-else
                :disabled="!row.isSelect"
                @click="setDefault(row)"
                >设为默认</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="save">保存</el-button>
    <el-button type="default" @click="cancel">取消</el-button>
  </el-card>
</template>

<script lang="ts">
import type {
  saleImageItemType,
  skuImageListType,
  skuInfoType,
  spuInfoItemType,
} from "@/api/spu";
import { defineComponent } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "AddSku",
});
</script>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { reqGetAttrInfo, type attrListType } from "@/api/attr";
import {
  reqSaleImageList,
  reqSaleAttrList,
  type saleImageListType,
  type saleAttrListType,
  reqAddSku,
} from "@/api/spu";
import useCategoryStore from "@/stores/category";

//拿pinia数据
const categoryStore = useCategoryStore();
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);

//定义一个枚举 代表组件状态
enum compStatus {
  SpuList,
  AddSpu,
  AddSku,
}

const emit = defineEmits<{
  (event: "changeStatus", status: number): void;
}>();

const cancel = () => {
  emit("changeStatus", compStatus["SpuList"]);
};

// 接收props
const props = defineProps<{
  spuInfo: spuInfoItemType;
}>();

//初始化数据接受列表
const attrList = ref<attrListType>([]);
const saleAttrList = ref<saleAttrListType>([]);
const spuImageList = ref<saleImageListType>([]);

const loading = ref(false);
//初始化发送三个列表请求
onMounted(async () => {
  const promise1 = reqGetAttrInfo(
    category1Id.value!,
    category2Id.value!,
    category3Id.value!
  );
  const promise2 = reqSaleAttrList(props.spuInfo.id!);
  const promise3 = reqSaleImageList(props.spuInfo.id!);

  try {
    loading.value = true;
    const result = await Promise.all([promise1, promise2, promise3]);
    attrList.value = result[0];
    saleAttrList.value = result[1];
    spuImageList.value = result[2];
    // console.log(result);
    attrList.value.forEach((item) => {
      item.attrIdValueId = "";
    });

    saleAttrList.value.forEach((item) => {
      item.saleAttrIdValueId = "";
    });
    spuImageList.value.forEach((item) => {
      item.isDefault = false;
    });
    loading.value = false;
  } catch (e: any) {
    ElMessage.error("请求列表信息失败:" + e.message);
  }
});
//初始化一个skuInfo，用来收集数据
const skuInfo = ref<skuInfoType>({
  category3Id: category3Id.value!, //三级分类id
  isSale: 1, //默认上架
  price: 0, //价格
  skuDefaultImg: "", //默认图片
  skuDesc: "", //描述
  skuName: "", //名称
  spuId: props.spuInfo.id!, //当前所在的spu的id
  tmId: props.spuInfo.tmId!, //当前所在的品牌id
  weight: "", //重量
  skuAttrValueList: [],
  skuImageList: [],
  skuSaleAttrValueList: [],
});

const handleSelectionChange = (val: saleImageListType) => {
  const unSelectList = spuImageList.value.filter((item) => {
    return !val.includes(item);
  });

  unSelectList.forEach((item) => {
    item.isDefault = false;
    if (item.imgUrl === skuInfo.value.skuDefaultImg) {
      skuInfo.value.skuDefaultImg = "";
    }
  });
  spuImageList.value.forEach((item) => {
    item.isSelect = true;
  });
  val.forEach((item) => {
    item.isSelect = true;
  });

  skuInfo.value.skuImageList = val.map((item) => {
    return {
      imgName: item.imgName!,
      imgUrl: item.imgUrl!,
      isDefault: "0",
      spuImgId: item.id!,
    };
  });
};

const setDefault = (row: saleImageItemType) => {
  spuImageList.value.forEach((item) => {
    item.isDefault = false;
    skuInfo.value.skuDefaultImg = "";
  });
  row.isDefault = true;
  skuInfo.value.skuDefaultImg = row.imgUrl!;
};

const save = async () => {
  // 整理平台属性
  attrList.value.forEach((item) => {
    if (item.attrIdValueId) {
      const [attrId, valueId] = item.attrIdValueId.split(":");
      skuInfo.value.skuAttrValueList.push({
        attrId: +attrId,
        valueId: +valueId,
      });
    }
  });
  // 整理销售属性
  saleAttrList.value.forEach((item) => {
    if (item.saleAttrIdValueId) {
      const [saleAttrId, saleAttrValueId] = item.saleAttrIdValueId.split(":");
      skuInfo.value.skuSaleAttrValueList.push({
        saleAttrId: +saleAttrId,
        saleAttrValueId: +saleAttrValueId,
      });
    }
  });
  // 发送请求
  try {
    await reqAddSku(skuInfo.value);
    ElMessage.success("提交成功");
    emit("changeStatus", compStatus["SpuList"]);
  } catch (e: any) {
    ElMessage.error("提交错误:" + e.message);
  }
};
</script>

<style scoped></style>
